package com.lj.exam.service.impl;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.lj.exam.dal.daointerface.SmsSendDAO;
import com.lj.exam.dal.daointerface.SmsTplDAO;
import com.lj.exam.dal.dataobject.SmsSendDO;
import com.lj.exam.dal.dataobject.SmsTplDO;
import com.lj.exam.model.SmsSendRequest;
import com.lj.exam.model.SmsSendResponse;
import com.lj.exam.service.SmsSendAliyunService;
import com.lj.exam.util.DateTimeUtils;

public class SmsSendAliyunServiceImpl implements SmsSendAliyunService {
	private int pools = 10;
	@Autowired
	private SmsTplDAO smsTplDAO;
	@Autowired
	private SmsSendDAO smsSendDAO;
	 //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAIhpQSAhcTsqyC";
    static final String accessKeySecret = "vWMgQF7ILgVTjD7nCH8uSCYu6AX3Iv";

	@Override
	public SmsSendResponse sendSms(SmsSendRequest req) throws ClientException {
		 //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        
        //根据短信编号 获取短信模板
        SmsTplDO smstpl = smsTplDAO.selectModelName(req.getSmsCode());
        String smstplValue = smstpl.getTplContent();
      
	    String smsValue = req.getSmsContents();
	   
		//根据短信模板和请求短信参数，组装 短信内容
		String smsSendContent=genSmsSendContent(smsValue,smstplValue);
		
        //必填:待发送手机号
        request.setPhoneNumbers(req.getMobile());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("保安考试系统");
        //必填:短信模板-可在短信控制台中找到
      
        request.setTemplateCode(req.getSmsCode());
        
        
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
      
		
        request.setTemplateParam(smsSendContent);
        
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        SmsSendResponse rsp = new SmsSendResponse();
    	SmsSendDO smsSendDO = getSmsSendInfo(req,smstpl);
		//短信流水表
		smsSendDAO.insert(smsSendDO);
        if(sendSmsResponse.getCode().equals("OK")){
        	rsp.setSmsCode("0000");
        	rsp.setSmsContent("ok");
        
        }else{
        	rsp.setSmsCode("9999");
        	rsp.setSmsContent("no");
        }
        return rsp;
	}
	private String genSmsSendContent(String param,String smstplValue) {
		
		List<String> params=Arrays.asList(param.split(",", -1));
		int repLen=smstplValue.split("%", -1).length-1;
		
		String sendVal=smstplValue;
		for(String paramVal:params){
			sendVal=sendVal.replaceFirst("%", paramVal);
		}
		return sendVal;
		
	}
	
	private SmsSendDO getSmsSendInfo(SmsSendRequest request, SmsTplDO smstpl) {
		SmsSendDO smsSendDO = new SmsSendDO();
		
		String seqNo=DateTimeUtils.formatLongFormat(new Date());
		
		int kindCode=Integer.parseInt(seqNo.substring(seqNo.length()-2));
		kindCode=kindCode%pools;
		Date recvDate=new Date();
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(recvDate);
		
		smsSendDO.setId(seqNo);
		smsSendDO.setUserId(request.getUserId());
		smsSendDO.setUserName(request.getUserName());
		smsSendDO.setCreateTime(recvDate);
		smsSendDO.setModifiedTime(recvDate);
		
		cal.add(Calendar.MINUTE, 10);
		
		smsSendDO.setRecvTime(cal.getTime());
		smsSendDO.setDay(cal.get(Calendar.DAY_OF_MONTH));
		smsSendDO.setEndTime(smstpl.getEndTime());
		smsSendDO.setExpiredTime(smstpl.getExpiredTime());
		smsSendDO.setStartTime(smstpl.getStartTime());
		
		smsSendDO.setValidTime(smstpl.getValidTime());
		smsSendDO.setCreator(request.getFromSys());
		smsSendDO.setModifier(request.getFromSys());
		smsSendDO.setMobile(request.getMobile());
		
		smsSendDO.setKindCode(kindCode);
		smsSendDO.setSmsContent(request.getSmsSendContent());
		smsSendDO.setSmsCode(request.getSmsCode());
		
		smsSendDO.setStatus("I");
		smsSendDO.setSourceCode(request.getSourceCode());
		smsSendDO.setPriority(request.getPriority());
		//待修改项
		smsSendDO.setSendTime(new Date());
		smsSendDO.setRespCode("0000");
		smsSendDO.setRespMsg("ok");
		return smsSendDO;
	}

	@Override
	public SmsSendResponse sendSmsExt(SmsSendRequest req) {
		// TODO Auto-generated method stub
		return null;
	}

}
